package com.example.elasticsearchhepler.strategy.aggregation;

import com.example.elasticsearchhepler.entity.common.AggregationParamEntity;
import com.example.elasticsearchhepler.exception.BizException;
import com.example.elasticsearchhepler.utils.EmptyUtil;
import com.example.elasticsearchhepler.utils.SpringContextUtil;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.LongBounds;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;

@Service(value = "dateHistogramParseAggregation")
public class DateHistogramParseAggregationServiceImpl implements ParseAggregationService {
    @Override
    public AggregationBuilder parseAggregation(AggregationParamEntity param) throws BizException {

        if (EmptyUtil.isEmpty(param.getStartDate())){
            throw new BizException(0,"开始日期不能为空");
        }

        if (EmptyUtil.isEmpty(param.getEndDate())){
            throw new BizException(0,"结束日期不能为空");
        }

        //指定返回日期区间，没有的返回0
        LongBounds extendedBounds = new LongBounds(param.getStartDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),param.getEndDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        DateHistogramAggregationBuilder aggregationBuilder = AggregationBuilders.dateHistogram(param.getName())
                .calendarInterval(DateHistogramInterval.DAY).format("yyyy-MM-dd").field(param.getField()).keyed(true).extendedBounds(extendedBounds);

        if (EmptyUtil.isEmpty(param.getSubAgg())){
            return aggregationBuilder;
        }
        for (AggregationParamEntity e:param.getSubAgg()) {
            ParseAggregationService service = (ParseAggregationService) SpringContextUtil.getBean(e.getType().toString()+"ParseAggregation");
            aggregationBuilder.subAggregation(service.parseAggregation(e));
        }
        return aggregationBuilder;
    }
}
